from django.shortcuts import render
from django.utils.datetime_safe import datetime
from django.views import View
from django.http import JsonResponse
from user.models import SysUser
from rest_framework_jwt.settings import api_settings
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from .models import Novel
from .pagination import CustomPagination
# Create your views here.
# class CustomPagination(PageNumberPagination):
#     page_size = 10
#     page_size_query_param = 'page_size'
#     max_page_size = 100

class NovelSerializer(serializers.ModelSerializer):
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M")

    class Meta:
        model = Novel
        fields = '__all__'

# 新增序列化器
# 删除 DateTimeField 格式化，改为普通字段
class NovelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Novel
        fields = '__all__'
# 新增API视图
# ... existing imports ...

class NovelListView(APIView):
    def get(self, request):
        queryset = Novel.objects.all()
        search_query = request.query_params.get('search', '')
        if search_query:
            queryset = queryset.filter(name__icontains=search_query)

        paginator = CustomPagination()
        page = paginator.paginate_queryset(queryset, request)
        if page is not None:
            serializer = NovelSerializer(page, many=True)
            # 修改为前端期望的响应格式
            return Response({
                'code': 200,
                'data': serializer.data,
                'total': queryset.count()  # 添加总记录数
            })

        serializer = NovelSerializer(queryset, many=True)
        return Response({'code': 200, 'data': serializer.data, 'total': queryset.count()})


# ... existing code ...

class TestUserView(View):

    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        print("token", token)
        if token is not None and token != '':
            # 采用 Models中的名字 查询user中所有的数据
            user_list = SysUser.objects.all()
            print(user_list, type(user_list))
            # 把对象数据转为字典类型
            user_dict = user_list.values()
            print(user_dict, type(user_dict))
            # 解析外层容器 把数据转存json 存入到list中
            userList = list(user_dict)
            print(userList, type(userList))
            #响应给前台的数据
            return JsonResponse({'code': 200, 'info': '测试成功','data':userList})
            #通过网页访问
        else:
            return JsonResponse({'code': 401, 'info': '未授权，没有访问权限'})


class JwtTestView(View):
    def get(self, request):
        user = SysUser.objects.get(username='admin', password='123456')
        # 获取 JWT 处理函数
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成载荷令牌
        # 将用户对象传递进去，获取到该对象的属性值
        payload = jwt_payload_handler(user)
        # 将属性值编码成jwt格式的字符串
        token = jwt_encode_handler(payload)
        print('token',token)
        return JsonResponse({'code': 200, 'token': token})

class LoginView(View):
    def post(self, request):
        username = request.GET.get("username")
        password = request.GET.get("password")
        try:
            user = SysUser.objects.get(username=username, password=password)
            # 获取 JWT 处理函数
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 生成载荷令牌
            # 将用户对象传递进去，获取到该对象的属性值
            payload = jwt_payload_handler(user)
            # 将属性值编码成jwt格式的字符串
            token = jwt_encode_handler(payload)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'info': '用户名或密码错误'})
        return JsonResponse({'code': 200, 'token':token, 'user':SysUserSerializers(user).data, 'info': '登录成功'})

class SysUserSerializers(serializers.ModelSerializer):
    class Meta:
        model = SysUser
        fields = '__all__'




class NovelStatusUpdateView(APIView):
    def patch(self, request, novel_id):
        try:
            novel = Novel.objects.get(id=novel_id)
            # 切换状态：0->1 或 1->0
            novel.status = 1 if novel.status == 0 else 0
            novel.save()
            return Response({
                'code': 200,
                'message': '状态更新成功',
                'status': novel.status
            })
        except Novel.DoesNotExist:
            return Response({
                'code': 404,
                'message': '小说不存在'
            }, status=404)
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器错误'
            }, status=500)



class NovelDeleteView(APIView):
    def delete(self, request, novel_id):
        try:
            novel = Novel.objects.get(id=novel_id)
            novel.delete()
            return Response({
                'code': 200,
                'message': '小说删除成功'
            })
        except Novel.DoesNotExist:
            return Response({
                'code': 404,
                'message': '小说不存在'
            }, status=404)
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器错误: ' + str(e)
            }, status=500)




# class NovelCreateView(APIView):
#     def post(self, request):
#         try:
#             serializer = NovelSerializer(data=request.data)
#             if serializer.is_valid():
#                 serializer.save()
#                 return Response({
#                     'code': 200,
#                     'message': '小说上架成功',
#                     'data': serializer.data
#                 })
#             return Response({
#                 'code': 400,
#                 'message': '数据验证失败',
#                 'errors': serializer.errors
#             }, status=400)
#         except Exception as e:
#             return Response({
#                 'code': 500,
#                 'message': '服务器错误: ' + str(e)
#             }, status=500)

class NovelCreateView(APIView):
    def post(self, request):
        try:
            # 准备数据，自动生成必要字段
            novel_data = {
                **request.data,
                'update_time': datetime.now().strftime('%Y-%m-%d %H:%M'),
                'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'status': request.data.get('status', 0)  # 默认上架状态
            }

            # 移除前端可能传入的id字段
            if 'id' in novel_data:
                del novel_data['id']

            serializer = NovelSerializer(data=novel_data)

            if serializer.is_valid():
                serializer.save()
                return Response({
                    'code': 200,
                    'message': '小说上架成功',
                    'data': serializer.data
                })
            return Response({
                'code': 400,
                'message': '数据验证失败',
                'errors': serializer.errors  # 返回具体错误信息
            }, status=400)

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            }, status=500)